package com.cgbsoft.financial.net;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Properties;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

/*
 * author:wudongdong
 */
public class BaseAccessor {
	private static String log = null;
	private static Uri PREFERRED_APN_URI = Uri
			.parse("content://telephony/carriers/preferapn");

	public static String deRequest(Context context, String urlString,
			HashMap<String, String> params) {
		try {

			URL url = new URL(urlString);
			HttpURLConnection uc = (HttpURLConnection) url.openConnection();
			uc.setConnectTimeout(20 * 1000);
			uc.setReadTimeout(20 * 1000);
			Cursor c = context.getContentResolver().query(PREFERRED_APN_URI,
					null, null, null, null);
			c.moveToFirst();
			String proxy = c.getString(c.getColumnIndex("proxy"));
			if (!"".equals(proxy) && proxy != null) {
				Properties prop = System.getProperties();
				System.getProperties().put("proxySet", "true");
				prop.setProperty("http.proxyHost", c.getString(c
						.getColumnIndex("proxy")));
				prop.setProperty("http.proxyPort", c.getString(c
						.getColumnIndex("port")));
				String authentication = c.getString(c.getColumnIndex("user"))
						+ ":" + c.getString(c.getColumnIndex("password"));
				String encodedLogin = Base64.encode(authentication);
				uc.setRequestProperty("Proxy-Authorization", " Basic "
						+ encodedLogin);
			}else{
				Properties prop = System.getProperties();
				System.getProperties().put("proxySet", "false");
				prop.setProperty("http.proxyHost","");
				prop.setProperty("http.proxyPort","");
			}
			c.close();

			uc.setRequestProperty("User-Agent", "Mozilla/5.0");

			uc.setDoInput(true);
			uc.setDoOutput(true);
			uc.setRequestMethod("POST");
			if (params != null && !params.isEmpty()) {
//				EncryptUtil.encryptNet(params);
				StringBuffer buf = new StringBuffer();
				for (String key : params.keySet()) {
					buf.append("&").append(key).append("=").append(
							params.get(key));
				}
				Log.d("request", buf.toString());
				buf.deleteCharAt(0);
				uc.getOutputStream().write(buf.toString().getBytes("UTF-8"));
				uc.getOutputStream().close();
			}
			InputStream content = (InputStream) uc.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					content, "UTF-8"));
			String line = in.readLine();// will refactory
			in.close();
			return line.trim();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public static String doGet(Context context, String urlString) {
		try {

			URL url = new URL(urlString);
			HttpURLConnection uc = (HttpURLConnection) url.openConnection();
			uc.setConnectTimeout(20 * 1000);
			uc.setReadTimeout(20 * 1000);
			Cursor c = context.getContentResolver().query(PREFERRED_APN_URI,
					null, null, null, null);
			c.moveToFirst();
			String proxy = c.getString(c.getColumnIndex("proxy"));
			if (!"".equals(proxy) && proxy != null) {
				Properties prop = System.getProperties();
				System.getProperties().put("proxySet", "true");
				prop.setProperty("http.proxyHost", c.getString(c
						.getColumnIndex("proxy")));
				prop.setProperty("http.proxyPort", c.getString(c
						.getColumnIndex("port")));
				String authentication = c.getString(c.getColumnIndex("user"))
						+ ":" + c.getString(c.getColumnIndex("password"));
				String encodedLogin = Base64.encode(authentication);
				uc.setRequestProperty("Proxy-Authorization", " Basic "
						+ encodedLogin);
			}else{
				Properties prop = System.getProperties();
				System.getProperties().put("proxySet", "false");
				prop.setProperty("http.proxyHost","");
				prop.setProperty("http.proxyPort","");
			}
			c.close();
			uc.setRequestProperty("User-Agent", "Mozilla/5.0");
			uc.setRequestMethod("GET");

			InputStream content = (InputStream) uc.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					content, "UTF-8"));
			String line = in.readLine();// will refactory
//			Log.d("response", line);
			in.close();
			return line.trim();
		} catch (Exception e) {
			return "";
		}
	}
	public static Bitmap getBitmapFromUrl(String imageUrl) {
		Bitmap bitmap = null;
		InputStream in = null;
		OutputStream out = null;

		try {
			URL url = new URL(imageUrl);
			in = new BufferedInputStream(url.openStream(), 4 * 1024);

			final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
			out = new BufferedOutputStream(dataStream, 4 * 1024);
			copy(in, out);
			out.flush();

			final byte[] data = dataStream.toByteArray();
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
			//Log.e(LOG_TAG, "bitmap returning something");
			return bitmap;
		} catch (IOException e) {
		} finally {
			closeStream(in);
			closeStream(out);
		}
		return null;
	}
	
	private static void copy(InputStream in, OutputStream out)
			throws IOException {
		byte[] b = new byte[4 * 1024];
		int read;
		while ((read = in.read(b)) != -1) {
			out.write(b, 0, read);
		}
	}

	private static void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
			}
		}
	}
	
	public static String connectURL(String dest_url, String commString){
        String rec_string = "";
        URL url = null;
        HttpURLConnection urlconn = null;
        try{
            url = new URL(dest_url);
            urlconn = (HttpURLConnection)url.openConnection();
            urlconn.setRequestProperty("Content-Type","text/xml; charset=UTF-8");
            urlconn.setRequestMethod(getMethod());
            urlconn.setDoInput(true);
            if(getMethod().equalsIgnoreCase("POST")){
                urlconn.setDoOutput(true);
                OutputStream out = urlconn.getOutputStream();
                out.write(commString.getBytes());
                out.flush();
                out.close();
            }
            BufferedReader rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            int ch;
            while((ch = rd.read()) > -1) 
                sb.append((char)ch);
            rec_string = sb.toString();
            rd.close();
            urlconn.disconnect();
        }catch(Exception e){
            log = String.valueOf(String.valueOf((new StringBuffer("请求错误:")).append(e.getMessage()).append(e.toString())));
            writeLog(log);
        }
        return rec_string;
    }

    private static String getMethod(){
    	return "POST";
    }

    private static void writeLog(String s){
    	Log.i("log  ", s);
    }
    

}
